package cn.lg.soar.system.biz.modules.monitor.controller;

import cn.lg.soar.common.util.IpUtil;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.system.api.constant.ModuleConst;
import cn.lg.soar.system.biz.modules.monitor.model.WebLogVO;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2024/2/3 22:45
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Tag(name = "服务器信息")
@RestController
@RequestMapping(ModuleConst.MODULE_NAME + "/web-log")
public class WebLogController {

    private final  static Logger LOGGER = LoggerFactory.getLogger("webLog");

    @PostMapping("push")
    public void push(@RequestBody List<WebLogVO> logs, HttpServletRequest request) {
        String remoteIp = IpUtil.getRemoteIp(request);
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();

        for (WebLogVO log : logs) {
            LOGGER.error(
                    "{} {} {} {}，{}，{}，{}，{}\n{}",
                    LocalDateTime.now(),
                    UserContext.getUserNullable(),
                    remoteIp,
                    operatingSystem.getDeviceType(),
                    operatingSystem.getName(),
                    userAgent.getBrowser().getName(),
                    log.getSource(),
                    log.getHref(),
                    log.getStack()
            );
        }
    }

}
